package taro.todolist.dbinfo;

import org.springframework.beans.factory.annotation.Value;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TableInfo {

    private String table_name;
    private List<Map<String, String>> table_info;

    public TableInfo(String table_name){
        this.table_name = table_name;
        this.table_info = new ArrayList<>();

        String dbname = "tarocake_team";
        String dbpasswd = "diding2014";

        String query = String.format(
                "SELECT * FROM information_schema.columns WHERE table_name = ? AND table_schema = '%s' ",
                dbname
        );

        try(
                Connection connection = DriverManager.getConnection(
                        String.format("jdbc:mysql://localhost:3306/%s", dbname),
                        "root",
                        dbpasswd);
                PreparedStatement preparedStatement = connection.prepareStatement(query)
        )
        {
            preparedStatement.setString(1, table_name);
            ResultSet resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();

            while (resultSet.next()) {
                Map<String, String> columnInfo = new HashMap<>();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    String columnName = metaData.getColumnName(i);
                    String columnValue = resultSet.getString(columnName);
                    // 注意：这里可能需要根据数据类型进行不同的处理，比如日期、数字等
                    columnInfo.put(columnName, columnValue);
                }
                table_info.add(columnInfo);
            }
        }
        catch (SQLException e)
        {
            System.out.println(
                    "[ERROR]请联系开发人员VincentZyu。 [ERROR_INFO]获取dbinfo时捕获异常: " + e.getMessage()
            );
//            e.printStackTrace();
        }

    }

    public String getTable_name() {
        return table_name;
    }

    public List<Map<String, String>> getTable_info() {
        return table_info;
    }

}
